import SingletonBase from "../TFrame/script/helper/SingleTonBase";

export default class DailyRewardManager extends SingletonBase {
    lastGetDateInMillSecond: number = 0;
    keyLastGetDate = "keyLastGetDate"

    lastGetDayIndex = -1
    keyLastGetDayIndex = "keyLastGetDayIndex"

    getItemWithDefault(key: string, value) {
        let pv = cc.sys.localStorage.getItem(key)
        if (pv == null) {
            pv = value
        }
        return pv
    }

    constructor() {
        super()
        this.load();
    }

    load() {
        this.lastGetDateInMillSecond = parseInt(this.getItemWithDefault(this.keyLastGetDate, 0));
        this.lastGetDayIndex = parseInt(this.getItemWithDefault(this.keyLastGetDayIndex, -1))
        console.log(`lastGetDayIndex:${this.lastGetDayIndex}`);
    }

    persist() {
        cc.sys.localStorage.setItem(this.keyLastGetDayIndex, this.lastGetDayIndex)
        cc.sys.localStorage.setItem(this.keyLastGetDate, this.lastGetDateInMillSecond);
    }

    isDayGot(dayIndex: number) {
        return dayIndex <= this.lastGetDayIndex;
    }

    /**
     * 当前可领取的天，如果上次领取的日期小于今天，且未领取完
     */
    currentCanGetDay() {
        let now = new Date();
        let lastGot = new Date(this.lastGetDateInMillSecond);
        console.log(`now(y:${now.getFullYear()}, m:${now.getMonth()}, d:${now.getDate()})`)
        console.log(`lastGetDateInMillSecond:${this.lastGetDateInMillSecond} lastGot(y:${lastGot.getFullYear()}, m:${lastGot.getMonth()}, d:${lastGot.getDate()})`)
        let ret = now.getDate() != lastGot.getDate();
        console.log('currentCanGetDay:' + ret);
        if (now.getDate() != lastGot.getDate() ||
            now.getMonth() != lastGot.getMonth() ||
            now.getFullYear() != lastGot.getFullYear()) {
            return this.lastGetDayIndex + 1;
        }
        return -1;
    }

    didGet() {
        this.lastGetDayIndex = this.lastGetDayIndex + 1;
        let now = new Date();
        this.lastGetDateInMillSecond = now.getTime();
        this.persist();
    }
}
